<?php
/**
 * Author: LaiGuiming
 * Time: 2017-11-27 18:05:51
 * Copyright (C) 2016 Longyan Wehome Message CO.,LTD.
 */

namespace app\admin\controller\sys;
use app\common\controller\BackEnd;

/**
 * 管理员控制器
 * Class User
 * @package app\admin\controller
 */
class User extends BackEnd
{
    protected $model;//模型对象
    protected $modelName;//模型名称
    protected $explain;//说明

    public function _initialize()
    {
        parent::_initialize();
        $this->model=D("user");
        $this->modelName="User";
        $this->explain="管理员";
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/save/del/loadData五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将app/admin/lib/traits/Crud.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 修改头像
     * @return mixed
     */
    public function head()
    {
        $this->saveLog("修改头像");
        return $this->fetch();
    }
    /**
     * 修改密码
     * @param int $id
     * @return mixed
     */
    public function pwd($id = -1)
    {
        $this->assign('data', $this->model->get($id));
        return $this->fetch();
    }

    /**
     * 新增
     * @param int $id
     * @return mixed
     */
    public function add($id = -1)
    {
        $this->assign('data', $this->model->get($id));
        $this->assign('roles', D("role")->select());
        return $this->fetch();
    }

    /**
     * 获取分页数据 bootstrap-table格式
     * @param int $limit
     * @param int $offset
     */
    public function loadData($limit = 10,$offset=0)
    {
        $where="status!=2";

        if(input("name")){
            $where.=" and login_name like '%".input("name")."%'";
        };

        $counts=$this->model->where($where)->count();
        $data=$this->model->where($where)->order('ct desc')->limit($offset,$limit)->select();

        //角色数组转成名称字符串
        for($i=0;$i<count($data);$i++){
            $role_name=D("role")->where("id in(".$data[$i]['roles'].")")->field("name")->select();
            if(count($role_name)>0){
                $data[$i]['role_name']=implode(",", $this->array2Roles($role_name));
            }else{
                $data[$i]['role_name']='';
            }
        }

        $res = array("rows" => $data, "total" => $counts);
        echo json_encode($res);
    }

    /**
     * 角色数组转成名称字符串
     * @param $a
     * @return array
     */
    function array2Roles($a){
        foreach($a as $v){
            $arr2[]=$v['name'];
        }
        return $arr2;
    }

    /**
     * 保存
     * @param string $id
     * @return string|void
     */
    public function save($id = '')
    {
        //校验
        $validate=validate($this->modelName);
        if(!$validate->check($_POST)){
            $this->resError($validate->getError());
            return;
        }

        $roles=implode(",", $_POST['roles']);
        $_POST['roles']=$roles;

        if ($id != '') {//修改
            $res = $this->model->allowField(true)->save($_POST,['id' => $id]);
            $this->saveLog("修改用户【".$_POST['user_name']."】");
        }else{//新增
            //判断登录名是否以存在
            $oldUser=$this->model->where("login_name='".$_POST['login_name']."'")->select();
            if(count($oldUser)>0){//用户已存在
                $this->resError("用户已存在，新增失败！");
                return;
            }
            //默认头像
            $_POST['head_img']="/public/static/admin/assets/img/profile_small.jpg";
            //默认密码
            $_POST['pwd']=md5("123456");
            $res = $this->model->allowField(true)->save($_POST);

            $this->saveLog("新增用户【".$_POST['user_name']."】");
        }
        $this->resData($res);
    }

    /**
     * 修改状态
     * @param string $id
     * @param int $status
     */
    public function status($id = '',$status=0)
    {
        $res = $this->model->update(['id' => $id, 'status' => $status]);
        $this->saveLog("修改用户状态，id:".$id.",status:".$status);
        $this->resData($res);
    }

    /**
     * 修改密码
     * @param string $id
     * @return string|void
     */
    public function updPwd($id = '',$oldPwd,$oldPwdVal)
    {
        if(md5($oldPwd)!=$oldPwdVal){//原密码不正确
            $this->resError("原密码不正确！");
            return;
        }

        if ($id != '') {
            $_POST['pwd']=md5($_POST['pwd']);
            $res = $this->model->allowField(true)->save($_POST,['id' => $id]);
        }

        $this->saveLog("修改密码");
        $this->resData($res);
    }
}